﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Reflection;

namespace iMan
{
    public class WMIVendor : IDisposable
    {
        protected static WMIVendor instance;
        protected ManagementScope scope;
        protected ConnectionOptions conn;
        protected static volatile object syncRoot = new object();

        private WMIVendor()
        {
            conn = new ConnectionOptions();
            scope = new ManagementScope("\\\\localhost", conn);
            scope.Options.Impersonation = ImpersonationLevel.Impersonate;
        }

        public WMIProcessInfo GetProcessInfoBy(int pid)
        {
            WMIProcessInfo info = new WMIProcessInfo();
            try
            {
                ObjectQuery query = new ObjectQuery(string.Format("select * from Win32_Process where ProcessID={0}", pid));
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                ManagementObjectCollection results = searcher.Get();
                PropertyInfo[] props = typeof(WMIProcessInfo).GetProperties();
                foreach (ManagementObject item in results)
                {
                    foreach (PropertyInfo propInfo in props)
                    {
                        propInfo.SetValue(info, item[propInfo.Name], null);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return info;
        }

        public static WMIVendor Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null) instance = new WMIVendor();
                    }
                }
                return instance;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            //TODO
        }

        #endregion
    }
}
